package cn.virens.common.easyexcel.dict;

import cn.virens.common.mybatis.entity.BaseEnum;
import cn.virens.common.util.core.Assert;
import cn.virens.common.util.core.objcet.ObjectUtil;
import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.reflect.ClassUtil;
import org.dromara.hutool.core.reflect.method.MethodUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;

import java.util.Map;
import java.util.function.BiConsumer;

public class ExcelDictUtil {
    /**
     * 调用枚举类的values方法
     */
    private static BaseEnum<?>[] invokeValues(Class<?> clazz) throws APIException {
        return MethodUtil.invokeStatic(MethodUtil.getMethod(clazz, "values"));
    }

    /**
     * 扫描指定包路径下的枚举，并返回对应values值
     */
    public static void scanEnums(String pkgs, BiConsumer<Class<?>, BaseEnum<?>[]> consumer) {
        for (String pkg : SplitUtil.split(pkgs, ",", true, true)) {
            scanEnum(pkg, consumer);
        }
    }

    /**
     * 扫描指定包路径下的枚举，并返回对应values值
     */
    public static void scanEnum(String pkg, BiConsumer<Class<?>, BaseEnum<?>[]> consumer) {
        for (Class<?> clazz : ClassUtil.scanPackage(Assert.isEmpty(pkg))) {
            if (clazz != null && BaseEnum.class.isAssignableFrom(clazz)) {
                consumer.accept(clazz, invokeValues(clazz));
            }
        }
    }

    /**
     * 通过调用对应字段的GET方法获取对应的字段值
     */
    private static String get(Object obj, String field) throws APIException {
        if (field != null && obj instanceof Map<?, ?> map) {
            return MapUtil.getStr(map, field);
        }

        return s(ObjectUtil.get(obj, field));
    }

    /**
     * 获取对应实体的name字段
     */
    public static String getName(Object item) {
        return get(item, "name");
    }

    /**
     * 获取对应实体的code字段
     */
    public static String getCode(Object item) {
        String answer = get(item, "code");
        if (StrUtil.isEmpty(answer)) {
            return get(item, "id");
        }

        return answer;
    }

    /**
     * 将任意对象转为字符串
     */
    public static String s(Object obj) {
        return ObjectUtil.toString(obj);
    }

}
